﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Earth;

namespace Earth
{
    public partial class FormMain : Form
    {
        private EarthDataContextDataContext context = null;

        public FormMain()
        {
            InitializeComponent();
        }

        private void LoadContinents()
        {
            try
            {
                this.context = new EarthDataContextDataContext();
                this.continentBindingSource.DataSource = context.Continents;
                buttonReload_Click(this, EventArgs.Empty);
            }
            catch (Exception)
            {                
                throw;
            }
        }

        private void LoadCountries()
        {            
            if (this.comboBoxCountries.Items.Count == 0)
            {
                this.comboBoxCountries.Enabled = false;
                this.comboBoxCountries.Text = String.Empty;
                this.textBoxLagnuage.Text = String.Empty;
                this.groupBoxCountinent.Text = String.Empty;
                this.buttonUploadImage.Enabled = false;
            }
            else
            {
                this.comboBoxCountries.Enabled = true;
                this.textBoxLagnuage.DataBindings.Clear();
                Binding bindLanguage = new Binding("Text", this.countryBindingSource, "Language");
                this.textBoxLagnuage.DataBindings.Add(bindLanguage);
                this.buttonUploadImage.Enabled = true;

                LoadImage();
            }
        }

        void bindPhoto_Format(object sender, ConvertEventArgs e)
        {
            if (e.DesiredType == typeof(Image))
            {
                if (e.Value != null)
                {
                    byte[] array = ((System.Data.Linq.Binary)e.Value).ToArray();
                    MemoryStream ms = new MemoryStream(array);
                    e.Value = Image.FromStream(ms);
                }
                else
                {
                    using (FileStream fs = File.OpenRead("../../no_image.gif"))
                    {
                        e.Value = Image.FromStream(fs);
                    }
                }
            }
        }

        private void listBoxContinents_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadCountries();
        }

        private void buttonUploadImage_Click(object sender, EventArgs e)
        {
            openFileDialogImage.ShowDialog();
        }

        private void openFileDialogImage_FileOk(object sender, CancelEventArgs e)
        {
            using(Stream file = openFileDialogImage.OpenFile())
            {
                byte[] image = new byte[file.Length];
                int offset = 0;
                while (true)
                {
                    int bytesRead = file.Read(image, offset, (int)file.Length - offset);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    offset += bytesRead;
                }
                int countryID = (int)comboBoxCountries.SelectedValue;
                EarthDataContextDataContext.UploadImage(countryID, image);
                buttonReload_Click(this, EventArgs.Empty);
            }
        }

        private void buttonReload_Click(object sender, EventArgs e)
        {
            this.context = new EarthDataContextDataContext();
            this.continentBindingSource.DataSource = context.Continents;
            this.listBoxContinents.SetSelected(0, true);
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            context.SubmitChanges();
        }

        private void buttonAddCountry_Click(object sender, EventArgs e)
        {
            FormAddCountry addCountry = new FormAddCountry();
            if (addCountry.ShowDialog() == DialogResult.OK)
            {
                Country newCountry = new Country()
                {
                    CountryName = addCountry.CountryName,
                    Language = addCountry.Language,
                    ContinentID = (int)listBoxContinents.SelectedValue
                };
                EarthDataContextDataContext.AddCountry(newCountry);
                buttonReload_Click(this, EventArgs.Empty);
            }
        }

        private void buttonDeleteCountry_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    EarthDataContextDataContext.DeleteCountry((int)this.comboBoxCountries.SelectedValue);
                    buttonReload_Click(this, EventArgs.Empty);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Couldn't perform delete");
            }
            
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            LoadContinents();
        }
        
        private void comboBoxCountries_SelectionChangeCommitted(object sender, EventArgs e)
        {
            LoadImage();
        }

        private void LoadImage()
        {
            if ((int)comboBoxCountries.SelectedValue > 0)
            {
                Country image = (from c in context.Countries
                                 where c.CountryID == (int)this.comboBoxCountries.SelectedValue
                                 select c).Single();

                if (image.Flag != null)
                {
                    this.pictureBoxFlag.DataBindings.Clear();
                    Binding bindPhoto = new Binding("Image", countryBindingSource, "Flag", true);
                    bindPhoto.Format += new ConvertEventHandler(bindPhoto_Format);
                    this.pictureBoxFlag.DataBindings.Add(bindPhoto);
                }
                else
                {
                    this.pictureBoxFlag.Image = this.pictureBoxFlag.InitialImage;
                }
            }
        }
    }
}